package demo.TCPtest;

import java.io.File;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import demo.util.FileMd5Utils;

public class FilesDirHelper {
	private static Logger logger = LoggerFactory.getLogger(FilesDirHelper.class);
	
	/**
	 * 
	 * @param fileDir 
	 * @param map
	 * @throws IOException 
	 * @throws NoSuchAlgorithmException 
	 */
	public static void buildMap(String rootDir,String fileDir,Map map)
	{
		File f = new File(rootDir+fileDir);
		if(f.isDirectory())
		{
			for(String s:f.list())
			{
				buildMap(rootDir,fileDir+"\\"+s,map);
			}
		}else
		{
			try {
				map.put(fileDir, FileMd5Utils.getHash(rootDir+fileDir));
			} catch (NoSuchAlgorithmException | IOException e) {
				logger.error("文件："+fileDir+",计算MD5码错误,请检查文件！");
				e.printStackTrace();
			}
		}
	}
	
	public static Map<String, String> comparisonDirMap(Map<String,String> serverMap,Map<String,String> clientMap)
	{
		Map<String, String> map = new HashMap<String, String>();
		for(Entry<String, String> entry :serverMap.entrySet())
		{
			//对比2个的md5码 如果一致则正确，不一致则需要修改  如果clientMap中没有 则md5一定不一致
			if(!entry.getValue().equals(clientMap.get(entry.getKey())))
			{
				map.put(entry.getKey(),entry.getValue());
			}
		}
		return map;
	}

	public static String print(byte[] buffer)
	{
		StringBuffer sb = new StringBuffer();
		for (byte b : buffer) {
			sb.append(b);
		}
		return sb.toString();
	}

	public static boolean compare(byte[] buffer,byte[] buffer1)
	{
		if(buffer.length != buffer1.length)
		{
			return false;
		}
		for (int i = 0; i < buffer.length; i++) {
			if(buffer[i] != buffer1[i])
			{
				return false;
			}
		}
		return true;
	}
}
